package com.jyxd.web.controller.basic;

import com.jyxd.web.data.basic.VitalSign;
import com.jyxd.web.data.dto.HttpResult;
import com.jyxd.web.data.user.User;
import com.jyxd.web.service.assessment.basic.VitalSignMergeService;
import com.jyxd.web.service.assessment.basic.VitalSignService;
import com.jyxd.web.service.dictionary.CommentItemService;
import com.jyxd.web.service.patient.PatientScoreItemService;
import com.jyxd.web.util.HttpCode;
import com.jyxd.web.util.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

import static com.jyxd.web.util.DateUtil.*;

@Api(tags = "生命体征表相关接口")
@Controller
@RequestMapping(value = "/vitalSign")
public class VitalSignController {

    private static Logger logger = LoggerFactory.getLogger(VitalSignController.class);

    @Autowired
    private VitalSignService vitalSignService;
    @Autowired
    private VitalSignMergeService vitalSignMergeService;
    @Autowired
    private PatientScoreItemService patientScoreItemService;

    @Autowired
    private CommentItemService commentItemService;

    /**
     * 增加一条生命体征表记录
     *
     * @return
     */
    @RequestMapping(value = "/insert")
    @ResponseBody
    public String insert(@RequestBody VitalSign vitalSign, HttpSession session) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "添加失败");
        Map<String, Object> map = new HashMap<>();
        map.put("status", 1);
        map.put("dataTime", vitalSign.getDataTime());
        map.put("code", vitalSign.getCode());
        map.put("patientId", vitalSign.getPatientId());
        //首先根据时间和code 和 病人主键id查询对象 是否已经有数据 如果有则新增失败
        List<VitalSign> vitalSignList = vitalSignService.queryDataByTimeAndCode(map);
        if (CollectionUtils.isEmpty(vitalSignList)) {
            vitalSign.setId(UUIDUtil.getUUID());
            vitalSign.setCreateTime(new Date());
            vitalSign.setCreateTime(new Date());
            vitalSign.setUpdateTime(new Date());
            vitalSign.setStatus(1);
            vitalSignService.insert(vitalSign);
            json.put("code", HttpCode.OK_CODE.getCode());
            json.put("msg", "添加成功");
        }
        return json.toString();
    }


    private void saveVisit(Date date) {
        VitalSign vitalSign = new VitalSign();
        vitalSign.setId(UUIDUtil.getUUID());
        vitalSign.setRowId(UUIDUtil.getUUID());
        vitalSign.setCreateTime(new Date());
        vitalSign.setUpdateTime(new Date());
        vitalSign.setPatientId("1db0ad3454ad4438a67b4d6e474f9c4b");
        vitalSign.setCode("spo2");
        vitalSign.setContent("123");
        vitalSign.setDataTime(date);
        vitalSign.setStatus(1);
        vitalSignService.insert(vitalSign);
        vitalSign.setId(UUIDUtil.getUUID());
        vitalSign.setCode("hr");
        vitalSign.setContent("456");
        vitalSignService.insert(vitalSign);
    }

    /**
     * 更新生命体征表记录状态
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public String update(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "更新失败");
        if (map != null && map.containsKey("id") && map.containsKey("status")) {
            VitalSign vitalSign = vitalSignService.queryData(map.get("id").toString());
            if (vitalSign != null) {
                vitalSign.setStatus((int) map.get("status"));
                vitalSignService.update(vitalSign);
                json.put("msg", "更新成功");
            } else {
                json.put("msg", "更新失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 编辑生命体征表记录单
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public String edit(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "编辑失败");
        if (map != null && map.containsKey("id") && map.containsKey("status") && map.containsKey("bedName")) {
            VitalSign vitalSign = vitalSignService.queryData(map.get("id").toString());
            if (vitalSign != null) {
                vitalSign.setStatus((int) map.get("status"));
                vitalSignService.update(vitalSign);
                json.put("msg", "编辑成功");
            } else {
                json.put("msg", "编辑失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());

        return json.toString();
    }

    /**
     * 删除生命体征表记录
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public String delete(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "删除失败");
        if (map.containsKey("id")) {
            VitalSign vitalSign = vitalSignService.queryData(map.get("id").toString());
            if (vitalSign != null) {
                vitalSign.setStatus(-1);
                vitalSignService.update(vitalSign);
                json.put("msg", "删除成功");
            } else {
                json.put("msg", "删除失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据主键id查询生命体征表记录
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/queryData", method = RequestMethod.POST)
    @ResponseBody
    public String queryData(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        if (map != null && map.containsKey("id")) {
            VitalSign vitalSign = vitalSignService.queryData(map.get("id").toString());
            if (vitalSign != null) {
                json.put("msg", "查询成功");
                json.put("data", JSONObject.fromObject(vitalSign));
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据条件分页查询生命体征表记录列表（也可以不分页）
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/queryList", method = RequestMethod.POST)
    @ResponseBody
    public String queryList(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        if (map != null && map.containsKey("start")) {
            int totalCount = vitalSignService.queryNum(map);
            map.put("start", ((int) map.get("start") - 1) * (int) map.get("size"));
            json.put("totalCount", totalCount);
        }
        List<VitalSign> list = vitalSignService.queryList(map);
        if (list != null && list.size() > 0) {
            json.put("msg", "查询成功");
            json.put("data", JSONArray.fromObject(list));
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据开始时间跨度分页查询生命体征表记录列表（也可以不分页）
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/getStartTimeList", method = RequestMethod.POST)
    @ResponseBody
    public String queryStartTimeList(@RequestBody(required = false) Map<String, Object> map) throws ParseException {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        if (map == null) {
            json.put("msg", "查询条件不存在，查询失败");
            return json.toString();
        }
        if (!map.containsKey("hour")) {
            json.put("msg", "查询时间跨度小时为空，查询失败");
            return json.toString();
        }
        if (!map.containsKey("startTime")) {
            json.put("msg", "查询开始时间为空，查询失败");
            return json.toString();
        }
        Date startTime = yyyyMMddHHmmssSdfToDate(String.valueOf(map.get("startTime")));
        Date endTime = getLaterHoursDate(startTime, Long.valueOf(String.valueOf(map.get("hour"))));
        map.put("startTime", yyyyMMddHHmmSdfToString(startTime));
        map.put("endTime", yyyyMMddHHmmSdfToString(endTime));
        if (map.containsKey("start")) {
            int totalCount = vitalSignService.queryNum(map);
            map.put("start", ((int) map.get("start") - 1) * (int) map.get("size"));
            json.put("totalCount", totalCount);
        }


        List<Map<String, Object>> list = vitalSignService.getListByStartTime(map);
        //处理吸氧方式数据
        for (int i = 0; i < list.size(); i++) {
            String inhaleOxygenStyleStr = String.valueOf(list.get(i).get("inhaleOxygenStyle"));//取出吸氧方式字符串
            if (inhaleOxygenStyleStr.contains(",")) {//如果有逗号，进行切割
                String[] split = inhaleOxygenStyleStr.split(",");
                List<String> inhaleOxygenStyleList = new ArrayList<String>();
                for (int a = 0; a < split.length; a++) {
                    //String description = commentItemService.queryData(String.valueOf(split[a])).getDescription();
                    //inhaleOxygenStyle inhaleoxygenstyle = new inhaleOxygenStyle(description);
                    //  commenItemDictionary.setDescription( commentItemService.queryData(String.valueOf(split[a])).getDescription());
                    inhaleOxygenStyleList.add(split[a]);
                }
                list.get(i).put("inhaleOxygenStyle", inhaleOxygenStyleList);
            }


        }
       /* for (int i=0;i<list.size();i++){
            String inhaleOxygenStyleStr = String.valueOf(list.get(i).get("inhaleOxygenStyle"));//去除吸氧方式字符串
            String[] split = inhaleOxygenStyleStr.split(",");
            List<inhaleOxygenStyle> inhaleOxygenStyleList = new ArrayList<inhaleOxygenStyle>();
            for (int a = 0;a<split.length;a++){
                inhaleOxygenStyle inhaleoxygenstyle = new   inhaleOxygenStyle(a+1,split[a]);
                inhaleOxygenStyleList.add(inhaleoxygenstyle);
            }
            list.get(i).put("inhaleOxygenStyle",inhaleOxygenStyleList);
        }
*/


        if (list != null && list.size() > 0) {
            json.put("msg", "查询成功");
            json.put("data", JSONArray.fromObject(list));
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 护理文书--护理单--生命体征--编辑一条记录（编辑时间除外）
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/editData")
    @ResponseBody
    public String editData(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "编辑失败");
        List<VitalSign> vitalSignList = vitalSignService.queryDataByTimeAndCode(map);
        if (!CollectionUtils.isEmpty(vitalSignList)) {
            VitalSign data = vitalSignList.get(0);
            data.setContent(map.get("content").toString());
            data.setUpdateTime(new Date());
            vitalSignService.update(data);
            json.put("code", HttpCode.OK_CODE.getCode());
            json.put("msg", "编辑成功");
        }
        return json.toString();
    }

    /**
     * 护理文书--护理单--生命体征--编辑一条记录（编辑时间）
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/editDataTime")
    @ResponseBody
    public String editDataTime(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "编辑失败");
        try {
            //先根据原来时间查询列表对象
            List<VitalSign> list = vitalSignService.queryListByTime(map);
            if (list != null && list.size() > 0) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                for (int i = 0; i < list.size(); i++) {
                    VitalSign vitalSign = list.get(i);
                    vitalSign.setDataTime(format.parse(map.get("time").toString()));
                    vitalSign.setUpdateTime(new Date());
                    vitalSignService.update(vitalSign);
                }
                json.put("code", HttpCode.OK_CODE.getCode());
                json.put("msg", "编辑成功");
            }
        } catch (Exception e) {
            logger.info("护理文书--护理单--生命体征--编辑一条记录（编辑时间）:" + e);
            return json.toString();
        }
        return json.toString();
    }

    /**
     * 护理文书--护理单--生命体征--根据病人主键id 查询生命体征列表
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/getList")
    @ResponseBody
    public String getList(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "暂无数据");
        try {
            if (map.containsKey("patientId") && StringUtils.isNotEmpty(map.get("patientId").toString())) {
                List<Map<String, Object>> list = vitalSignService.getList(map);
                if (list != null && list.size() > 0) {
                    json.put("data", JSONArray.fromObject(list));
                    json.put("code", HttpCode.OK_CODE.getCode());
                    json.put("msg", "查询成功");
                }
            } else {
                json.put("code", HttpCode.NO_PATIENT_CODE.getCode());
                json.put("msg", "请先选择病人");
            }
        } catch (Exception e) {
            logger.info("护理文书--护理单--生命体征--根据病人主键id 查询生命体征列表:" + e);
            return json.toString();
        }
        return json.toString();
    }

    /**
     * 护理文书--护理单--生命体征--删除整行
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/deleteOldData")
    @ResponseBody
    public String deleteOldData(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "删除失败");
        json.put("data", new ArrayList<>());
        try {
            List<VitalSign> list = vitalSignService.queryListByTime(map);
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    VitalSign vitalSign = list.get(i);
                    vitalSign.setStatus(-1);
                    vitalSign.setUpdateTime(new Date());
                    vitalSignService.update(vitalSign);
                }
                json.put("data", JSONArray.fromObject(list));
                json.put("code", HttpCode.OK_CODE.getCode());
                json.put("msg", "删除成功");
            }
        } catch (Exception e) {
            logger.info("护理文书--护理单--生命体征--删除整行:" + e);
            return json.toString();
        }
        return json.toString();
    }


    /**
     * 护理文书--护理单--生命体征--删除整行
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/deleteData")
    @ResponseBody
    public String deleteData(@RequestBody(required = false) Map<String, Object> map) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg", "删除失败");
        json.put("data", new ArrayList<>());
        try {
            List<VitalSign> list = vitalSignService.queryDataByTimeAndCode(map);
            if (CollectionUtils.isEmpty(list)) {
                json.put("msg", "无数据，删除失败");
            } else {
                list.forEach(vitalSign -> {
                    vitalSign.setStatus(-1);
                    vitalSign.setUpdateTime(new Date());
                    vitalSignService.update(vitalSign);
                });
                json.put("data", JSONArray.fromObject(list));
                json.put("code", HttpCode.OK_CODE.getCode());
                json.put("msg", "删除成功");
            }
        } catch (Exception e) {
            logger.info("护理文书--护理单--生命体征--删除整行:" + e);
            return json.toString();
        }
        return json.toString();
    }

    /**
     * 保存一条生命体征表记录
     *
     * @return
     */
    @RequestMapping(value = "/saveData")
    @ResponseBody
    public String saveData(@RequestBody VitalSign vitalSign, HttpSession session) {
        //return saveVitalSign(vitalSign, session).toString();
        return "";
    }

    /**
     * 保存一条生命体征表记录
     *
     * @return
     */
    @RequestMapping(value = "/saveDataList")
    @ResponseBody
    public String saveDataList(@RequestBody List<VitalSign> vitalSignList, HttpSession session) {
        AtomicReference<JSONObject> json = new AtomicReference<>(new JSONObject());
        json.get().put("code", HttpCode.FAILURE_CODE.getCode());
        json.get().put("data", new ArrayList<>());
        json.get().put("msg", "添加失败");
        if (CollectionUtils.isEmpty(vitalSignList)) {
            return json.toString();
        }
        //由于前端无法修改list第一次新增的数据中的rowid，需要在后端先循环判断list中是否有正常id，如果有，则给list中所有条目的rowid改为正常id，如果没有，则说明是新增的数据，保持add即可
        String rowid = "add";
        for (VitalSign vitalsign : vitalSignList) {
            if (!vitalsign.getRowId().equals("add")) {
                rowid = vitalsign.getRowId();
                break;
            }
        }
        for (VitalSign vitalsign : vitalSignList) {
            vitalsign.setRowId(rowid);
        }


        String rowId = UUIDUtil.getUUID();
        vitalSignList.forEach(vitalSign -> {
            //vitalSign.setRowId(rowId);
            json.set(saveVitalSign(vitalSign, session, rowId));
        });
        return json.toString();
    }

    @ApiOperation("同步监护仪数据到生命体征表")
    @RequestMapping(value = "/syncMonitorData", method = RequestMethod.POST)
    @ResponseBody
    public HttpResult syncMonitorDataOnVitalSign(@RequestBody Map<String, String> map, HttpSession session) throws Exception {
        return vitalSignMergeService.syncVitalSignMerge(map, (User) session.getAttribute("user"));
    }

    private JSONObject saveVitalSign(VitalSign vitalSign, HttpSession session, String rowid) {
        JSONObject json = new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data", new ArrayList<>());
        json.put("msg", "添加失败");
        try {
            if (StringUtils.isNotEmpty(vitalSign.getPatientId())) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Map<String, Object> map = new HashMap<>();
                map.put("status", 1);
                //map.put("dataTime", format.format(vitalSign.getDataTime()));
                map.put("code", vitalSign.getCode());
                map.put("patientId", vitalSign.getPatientId());
                map.put("rowId", vitalSign.getRowId());
                if (vitalSign.getRowId().equals("add")) {
                    vitalSign.setId(UUIDUtil.getUUID());
                    vitalSign.setCreateTime(new Date());
                    vitalSign.setUpdateTime(new Date());
                    vitalSign.setStatus(1);
                    //String rowId = UUIDUtil.getUUID();
                    vitalSign.setRowId(rowid);
                    /*if (StringUtils.equals(vitalSign.getCode(), "glasgow")) {
                        if (CollectionUtils.isEmpty(vitalSign.getGlasgowMap())) {
                            json.put("msg", "添加glasgow评分失败，评分数据不能为空");
                            return json;
                        }
                        saveGlasgow(vitalSign.getGlasgowMap(), (User) session.getAttribute("user"));
                    }*/
                    vitalSignService.insert(vitalSign);
                    json.put("code", HttpCode.OK_CODE.getCode());
                    json.put("msg", "添加成功");
                } else {
                    List<VitalSign> vitalSignList = vitalSignService.queryDataByTimeAndCode(map);
                    System.out.println("data不为空，code为" + map.get("code").toString() + "修改为" + vitalSign.getContent());
                    if (!CollectionUtils.isEmpty(vitalSignList)) {
                        VitalSign data = vitalSignList.get(0);
                        data.setContent(vitalSign.getContent());
                        data.setUpdateTime(new Date());
                        data.setDataTime(vitalSign.getDataTime());
                       /* if (StringUtils.equals(vitalSign.getCode(), "glasgow")) {
                            if (CollectionUtils.isEmpty(vitalSign.getGlasgowMap())) {
                                json.put("msg", "添加glasgow评分失败，评分数据不能为空");
                                return json;
                            }
                            saveGlasgow(vitalSign.getGlasgowMap(), (User) session.getAttribute("user"));
                        }*/
                        vitalSignService.update(data);
                        json.put("code", HttpCode.OK_CODE.getCode());
                        json.put("msg", "添加成功");
                    } else {
                        System.out.println("data为空，code为" + map.get("code").toString());
                        vitalSign.setId(UUIDUtil.getUUID());
                        vitalSign.setCreateTime(new Date());
                        vitalSign.setUpdateTime(new Date());
                        vitalSign.setStatus(1);
//                        String rowId = UUIDUtil.getUUID();
                        //                       vitalSign.setRowId(rowid);
                       /* if (StringUtils.equals(vitalSign.getCode(), "glasgow")) {
                            if (CollectionUtils.isEmpty(vitalSign.getGlasgowMap())) {
                                json.put("msg", "添加glasgow评分失败，评分数据不能为空");
                                return json;
                            }
                            saveGlasgow(vitalSign.getGlasgowMap(), (User) session.getAttribute("user"));
                        }*/
                        vitalSignService.insert(vitalSign);
                        json.put("code", HttpCode.OK_CODE.getCode());
                        json.put("msg", "添加成功");
                    }

                }
            } else {
                json.put("code", HttpCode.NO_PATIENT_CODE.getCode());
                json.put("msg", "请先选择病人");
            }
        } catch (Exception e) {
            logger.info(":" + e);
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 新增glasgow评分
     *
     * @param map
     * @param user
     * @throws ParseException
     */
    private void saveGlasgow(Map<String, Object> map, User user) throws ParseException {
        patientScoreItemService.insertPatientScore(map, user);
    }

    public class inhaleOxygenStyle {
        private String description;

        //构造注入
        public inhaleOxygenStyle(String description) {
            this.description = description;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }
    }


}
